package cn.com.dycc.sys_manage.menusysmanagement.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.sys_manage.dictionarysysmanagement.dao.DictionaryDao;
import cn.com.dycc.sys_manage.menusysmanagement.dao.MenuDao;
import cn.com.dycc.sys_manage.menusysmanagement.entity.Menu;
import cn.com.dycc.sys_manage.menusysmanagement.entity.MenuResult;
import cn.com.dycc.sys_manage.menusysmanagement.entity.MenuResultList;
import cn.com.dycc.sys_manage.menusysmanagement.entity.UserMenuResult;
import cn.com.dycc.sys_manage.menusysmanagement.param.MenuListParam;
import cn.com.dycc.sys_manage.rolesysmanagement.dao.RoleMenuDao;
import cn.com.dycc.sys_manage.rolesysmanagement.service.RoleNotFoundException;
import cn.com.dycc.sys_manage.usersysmanagement.dao.UserDao;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserIndexResult;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserPart;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.IntegerUtil;
import cn.com.dycc.util.MenuTree;
import cn.com.dycc.util.Paging;


/**
 * 
 * Description: 菜单的业务处理层
 * Author: KevinLee
 * Version: 1.0
 * Create Date Time: 2017年8月6日 上午11:30:30.
 * Update Date Time: 2017年8月8日 上午9:35:30.
 * @see
 */
@Service("menuService")
@Transactional
public class MenuServiceImpl implements MenuService{
	
	
	@Resource(name="menuDao")
	private MenuDao menuDao;
	
	@Resource(name="roleMenuDao")
	private RoleMenuDao roleMenuDao;
	
	@Resource(name="dictionaryDao")
	private DictionaryDao dictionaryDao;
	
	@Resource(name="userDao")
	private UserDao userDao;
	
	@Resource(name="paging")
	private Paging paging;
	
	//新增菜单
	public String addMenu(HttpServletRequest request,Menu menu) throws MenuNotFoundException,RoleNotFoundException {
		
		String opt_user_id = request.getSession().getAttribute("id").toString();
		String org_id = request.getSession().getAttribute("org_id").toString();
		if(opt_user_id==null){
			throw new MenuNotFoundException("请登录！");
		}
//		menu.setOpt_user_id(opt_user_id);
//		menu.setOrg_id(org_id);
		
		Menu createMenu = new Menu();
		//设置菜单id
		String menuNo = menu.getMenu_no();
		if(menuNo==null||menuNo.trim().isEmpty()){
			throw new MenuNotFoundException("请输入菜单序号！");
		}
		boolean b = IntegerUtil.isNumeric(menuNo);
		if(b==false){
			throw new MenuNotFoundException("菜单序号请输入整型！");
		}
		Menu me = menuDao.findMenuByMenuNo(menuNo);
		if(me!=null){
			throw new MenuNotFoundException("菜单序号已存在！");
		}
		//设置菜单名称
		String menuName = menu.getMenu_name();
		if(menuName==null||menuName.trim().isEmpty()){
			throw new MenuNotFoundException("请输入菜单名称！");
		}
		//平台标识
		String sys_flag = menu.getSys_flag();
		//源生或H5页面的标识
		String h5_flag = menu.getH5_flag();
		if(h5_flag==null||h5_flag.trim().isEmpty()){
			throw new MenuNotFoundException("请选择菜单标识！");
		}
		
		//登录用户组织id
//		String org_id = menu.getOrg_id();
//		String org_id =null;
		//设置Pid
		String pid = menu.getPid();
		Menu mu_name = menuDao.findMenuByMenuName(menuName,sys_flag,null,pid);
	//	System.out.println(mu_name);
		if(mu_name!=null){
			throw new MenuNotFoundException("菜单名称已存在");
		}
		//设置是否可以打开程序
		String menuOpenLocal = menu.getOpen_local();
		if(menuOpenLocal==null||menuOpenLocal.trim().isEmpty()){
			throw new MenuNotFoundException("请输入程序打开路径");
		}
		//设置打开程序方式
		String menuProgram = menu.getProgram();
		if(menuProgram==null||menuName.trim().isEmpty()){
			throw new MenuNotFoundException("请输入打开方式");
		}else if(!"MENU".equals(menuProgram)&&"左帧".equals(menuOpenLocal)){
			throw new MenuNotFoundException("打开路径不为“MENU”下，请将打开方式更改为右帧！");
		}else if("MENU".equals(menuProgram)&&"右帧".equals(menuOpenLocal)){
			throw new MenuNotFoundException("打开路径为“MENU”下，请将打开方式更改为左帧！");
		}
		//设置Pid
		if(pid==null||pid.trim().isEmpty()){
			throw new MenuNotFoundException("请输入父节点！");
		}
		if("0".equals(pid)){
			createMenu.setPid(pid);
//			throw new MenuNotFoundException("父节点不能为最顶级0！");
		}else{
			//设置pid不为0的情况下，有这个id存在才能当做pid
			int count = menuDao.findAllMenuNo(pid,sys_flag,null);
			if(count<=0){
				throw new MenuNotFoundException("父节点错误!");
			}	
		}
		//登录用户id
//		String opt_user_id = menu.getOpt_user_id();
//		String format = "yyyy-MM-dd HH:mm:ss";
//		String update_date = DateUtil.getNowDate(format);	
//		createMenu.setUpdate_date(update_date);
//		createMenu.setUpdate_user_id(opt_user_id);
		createMenu.setMenu_no(menuNo);
		createMenu.setSys_flag(sys_flag);
		createMenu.setOrg_id(org_id);
		createMenu.setOpt_user_id(opt_user_id);
		createMenu.setPid(pid);
		createMenu.setMenu_name(menuName);
		createMenu.setOpen_local(menuOpenLocal);
		createMenu.setProgram(menuProgram);
		createMenu.setH5_flag(h5_flag);
		//分别设置是否隐藏，排序号，图标，可否移动
		Integer menuOrderNo = menu.getOrder_no();
		if(menuOrderNo==null){
			createMenu.setOrder_no(null);
		}
		String menuIcon = menu.getMenu_icon();
		String hidden = menu.getHidden();
		//是否隐藏
		if(hidden==null){
			createMenu.setHidden("N");
		}
		createMenu.setOrder_no(menuOrderNo);
		createMenu.setMenu_icon(menuIcon);
		String id_dro = menu.getId_dro();
		if(id_dro==null){
			createMenu.setId_dro("N");
		}
		
		int addMenu = menuDao.addMenu(createMenu);
		
		if(addMenu<=0){
			throw new MenuNotFoundException("增加菜单失败！");
		}
		return "增加成功！";
	}

	//查询所有的菜单信息
	public List<Object> findAllMenu(HttpServletRequest request,String sys_flag) throws MenuNotFoundException,RoleNotFoundException{
		if(sys_flag==null){
			throw new MenuNotFoundException("选择查询的平台菜单!");
		}
		
//		String org_id = request.getSession().getAttribute("org_id").toString();
		//菜单中组织id不纳入查询条件
		String org_id = null;
		List<Menu> list = new ArrayList<Menu>();
		try {
			list = menuDao.findAllMenu(sys_flag,org_id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new MenuNotFoundException("查询失败！请稍后再试");
		}

		MenuTree menuTree = new MenuTree();
		return menuTree.menuList(list);
	}
	
	
	//删除选定的菜单信息
	public boolean deleteMenuByMenuNo(String menuNo) throws MenuNotFoundException,RoleNotFoundException{
		if(menuNo==null){
			throw new MenuNotFoundException("未选定指定删除的菜单");
		}
		Menu selectMenu = menuDao.findMenuByMenuNo(menuNo);
		if(selectMenu==null){
			throw new MenuNotFoundException("该菜单未存在");
		}
		
		
		int deleteMenu = menuDao.deleteMenuByMenuNo(menuNo);
		if(deleteMenu<=0){
			throw new MenuNotFoundException("删除失败！");
		}
		return true;
	}
	
	//根据菜单id查询菜单信息
	public MenuResult queryTheMenubyMenuId(String menuNo) throws MenuNotFoundException,RoleNotFoundException {
		if(menuNo==null){
			throw new MenuNotFoundException("未选定指定查询的菜单");
		}
		MenuResult selectMenu = menuDao.queryTheMenubyMenuId(menuNo);
		if(selectMenu==null){
			throw new MenuNotFoundException("该菜单未存在");
		}
		return selectMenu;
	}
	
	//根据菜单id更新菜单信息
	public String updateMenuByMenuNo(HttpServletRequest request,Menu menu) throws MenuNotFoundException,RoleNotFoundException{
		
		String update_user_id = request.getSession().getAttribute("id").toString();
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		Menu updateMenu = new Menu();
		String menuNo = menu.getMenu_no();
		Menu m = menuDao.findMenuByMenuNo(menuNo);
		if(m==null){
			throw new MenuNotFoundException("菜单不存在！");
		}
		updateMenu.setMenu_no(menuNo);
		//设置菜单名称
		String menuName = menu.getMenu_name();
		if(menuName==null||menuName.trim().isEmpty()){
			throw new MenuNotFoundException("请输入菜单名称！");
		}
		//平台标识
		String sys_flag = menu.getSys_flag();
		//组织标识
//		String org_id = menu.getOrg_id();
		String pid = menu.getPid();
		//判断菜单同级不同名
		Menu o_menu = menuDao.findMenuByMenuNo(menuNo);
		if(!(menuName.equals(o_menu.getMenu_name()))){
			Menu m_name = menuDao.findMenuByMenuName(menuName,sys_flag,null,pid);
			if(m_name!=null){
				throw new MenuNotFoundException("菜单名称已存在");
			}
		}
		
		String h5_flag = menu.getH5_flag();

		updateMenu.setMenu_name(menuName);
		//设置是否可以打开程序
		String menuOpenLocal = menu.getOpen_local();
		if(menuOpenLocal==null||menuOpenLocal.trim().isEmpty()){
			throw new MenuNotFoundException("请输入程序打开路径");
		}
		updateMenu.setOpen_local(menuOpenLocal);
		//设置打开程序方式
		String menuProgram = menu.getProgram();
		String menuPid = menu.getPid();
		if(menuProgram==null||menuName.trim().isEmpty()){
			throw new MenuNotFoundException("请输入打开方式");
		}else if(!"MENU".equals(menuProgram)&&"左帧".equals(menuOpenLocal)){
			throw new MenuNotFoundException("打开路径不为“MENU”下，请将打开方式更改为右帧！");
		}else if("MENU".equals(menuProgram)&&"右帧".equals(menuOpenLocal)){
			throw new MenuNotFoundException("打开路径为“MENU”下，请将打开方式更改为左帧！");
		}
		updateMenu.setProgram(menuProgram);
		//分别设置是否隐藏，排序号，图标
		String menuHidden = menu.getHidden();
		Integer menuOrderNo = menu.getOrder_no();
		if(menuOrderNo==null){
			updateMenu.setOrder_no(null);
		}
		//更新人id
//		String update_user_id = menu.getUpdate_user_id();
		updateMenu.setUpdate_user_id(update_user_id);
		//更新时间
		String format = "yyyy-MM-dd HH:mm:ss";
		String update_date = DateUtil.getNowDate(format);
		updateMenu.setUpdate_date(update_date);
		String menuIddro = menu.getId_dro();
		updateMenu.setId_dro(menuIddro);
		updateMenu.setPid(menuPid);
		updateMenu.setSys_flag(sys_flag);
		updateMenu.setH5_flag(h5_flag);
		String menuIcon = menu.getMenu_icon();
		updateMenu.setHidden(menuHidden);
		updateMenu.setOrder_no(menuOrderNo);
		updateMenu.setMenu_icon(menuIcon);
		updateMenu.setOrg_id(org_id);
		
		int renewal = menuDao.updateMenuByMenuNo(updateMenu);
		if(renewal<=0){
			throw new MenuNotFoundException("更新失败！");
		}
		return "更新成功！";
	}
	
	
	//根据用户id查询用户菜单的信息，用于用户的菜单的显示 pc ,手机 ，微信
	public List<Object> findMenuInfoByMap(HttpServletRequest request,String sys_flag) throws MenuNotFoundException,RoleNotFoundException {
		
		String user_id = request.getSession().getAttribute("id").toString();
		if(user_id==null){
			throw new MenuNotFoundException("请登录！");
		}
//		String org_id = request.getSession().getAttribute("org_id").toString();
		
		//菜单中组织id不纳入查询条件
		String org_id = null;
		
		List<Object> listObject = new ArrayList<Object>();
		
		List<Menu> listMenu = new ArrayList<Menu>();
		//PC端
		if("1".equals(sys_flag)){
			listMenu = menuDao.findMenuInfoByMap(user_id,sys_flag,org_id);
			MenuTree menuTree = new MenuTree();
			listObject = menuTree.menuList(listMenu);
		}else{
			//手机，微信
			List<Menu> menuList = menuDao.findInfoBySysFlag(user_id, sys_flag,org_id);
			UserPart userPart = userDao.reasonIdfindUser(user_id, org_id);
			UserMenuResult umr = new UserMenuResult();
			umr.setListMenu(menuList);
			umr.setUserPart(userPart);
			listObject.add(umr);
		}
		return listObject;
	}
	
	//查询所有菜单，排序
	public List<Map<String,Object>> selectAllMenuByTopDeptNo(HttpServletRequest request,String sys_flag){
		//pid为0的菜单
		
		//String org_id = request.getSession().getAttribute("org_id").toString();
		
		//菜单中组织id不纳入查询条件
		String org_id = null;
		
		List<String> menuId = menuDao.selMenuNoByPidOf(sys_flag,org_id);
//		System.out.println(menuId);
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> listMenu = new ArrayList<Map<String,Object>>();
		try {
	 		for(String id : menuId){
	 			//查询pid为0下面的子菜单
	 			list = menuDao.findAllMenuByShowChildLst(id);
	 //			System.out.println(list);
//	 			for(int j = 0 ; j<list.size();j++){
//	 				//判断更新人是否存在
//	 				String update_user_id_key = "update_user_id";
//	 				boolean contains = list.get(j).containsKey(update_user_id_key);
//	 				
//	 				if(contains){
//	 					String update_user_id = 
//	 	 						list.get(j).get("update_user_id").toString();
//	 					String update_username = userDao.findUserNameByUserId(update_user_id);
//	 	 				list.get(j).put("update_username", update_username);
//	 				}
//	 				
//	 			}
	 			listMenu.addAll(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new MenuNotFoundException("查询失败！");
		}

		return listMenu;
	}
	
	//查询全部菜单 用户菜单列表展示 HttpServletRequest request,
	public List<MenuResultList> findMenuList(HttpServletRequest request,MenuListParam menuListParam)
			throws MenuNotFoundException, RoleNotFoundException {
		
//		String org_id = request.getSession().getAttribute("org_id").toString();
//		String org_id = "1";
		//菜单中组织id不纳入查询条件
		String org_id = null;
		
		String sys_flag = menuListParam.getSys_flag();
		if(sys_flag==null || sys_flag.trim().isEmpty()){
			throw new MenuNotFoundException("菜单标识不能为空！");
		}
		
		Integer limit = menuListParam.getLimit();
		Integer page = menuListParam.getPage();
		
		if(page!=null&&page<=0){
			throw new MenuNotFoundException("开始页码为1！");
		}
		
		Integer start = null;
		if(limit==null&&page!=null){
			limit = paging.getPageSize();
			start=(page-1)*limit;
		}
		if(page==null){
			start = null;
			limit = null;
		}
		if(limit!=null&&page!=null){
			start = limit*(page-1);
		}
		
		menuListParam.setLimit(limit);
		menuListParam.setStart(start);
		menuListParam.setOrg_id(org_id);
		
		List<MenuResultList> listMenu = new ArrayList<MenuResultList>();
//		List<Object> listObject = new ArrayList<Object>();
		
		try {
			listMenu = menuDao.findMenuList(menuListParam);
//			MenuList menuList = new MenuList();
//			listObject = menuList.menuList(listMenu);
		} catch (Exception e) {
			e.printStackTrace();
			throw new MenuNotFoundException("查询失败！请稍后重试");
		}
		
		return listMenu;
	}

	//查询全部菜单 用户菜单列表展示的统计条数
	public String countMenuList(HttpServletRequest request, MenuListParam menuListParam)
			throws MenuNotFoundException, RoleNotFoundException {
		
//		String org_id = request.getSession().getAttribute("org_id").toString();
		
		//菜单中组织id不纳入查询条件
		String org_id = null;
		
		String sys_flag = menuListParam.getSys_flag();
		if(sys_flag==null || sys_flag.trim().isEmpty()){
			throw new MenuNotFoundException("菜单标识不能为空！");
		}
		
		String menu_name = menuListParam.getMenu_name();
		String count = menuDao.countMenuList(menu_name, sys_flag, org_id);
		
		return count;
	}
	
	//20180614查询用户菜单和用户信息
	public List<Object> findMenuAndUserInfo(HttpServletRequest request, String sys_flag)
			throws MenuNotFoundException, RoleNotFoundException {
		String user_id = request.getSession().getAttribute("id").toString();
		if(user_id==null){
			throw new MenuNotFoundException("请登录！");
		}
//		String org_id = request.getSession().getAttribute("org_id").toString();
		//菜单中组织id不纳入查询条件
		String org_id = null;
		
		List<Object> listObject = new ArrayList<Object>();
		
		List<Object> menu_list = new ArrayList<Object>();
		
		List<Menu> listMenu = new ArrayList<Menu>();
		//PC端
		if("1".equals(sys_flag)){
			//菜单
			Map<String,List<Object>> menu_map = new HashMap<String,List<Object>>();
			//用户
			Map<String,UserIndexResult> user_map = new HashMap<String,UserIndexResult>();
			
			listMenu = menuDao.findMenuInfoByMap(user_id,sys_flag,org_id);
			MenuTree menuTree = new MenuTree();
			menu_list = menuTree.menuList(listMenu);
			
			UserIndexResult indexUserInfo = userDao.indexUserInfo(user_id);
			
			menu_map.put("menu", menu_list);
			user_map.put("user", indexUserInfo);
			
			listObject.add(menu_map);
			listObject.add(user_map);
			
		}else{
			//手机，微信
			List<Menu> menuList = menuDao.findInfoBySysFlag(user_id, sys_flag,org_id);
			UserPart userPart = userDao.reasonIdfindUser(user_id, org_id);
			UserMenuResult umr = new UserMenuResult();
			umr.setListMenu(menuList);
			umr.setUserPart(userPart);
			listObject.add(umr);
		}
		return listObject;
	}
}
